import {API_HOST, API_PROXY} from "@/config.js"
import defaultAvatar from '@/static/icon/logo.png'

/**
 * 组装接口url
 */
export const packApiUrl = (url = '') => {
  if (url.slice(0, 4) === 'http') return url
  else return `${API_HOST}${API_PROXY}${url}`
}

/**
 * 对象数组去重
 * arr: Array
 * key: 唯一标识 String
 */
export const unique = (arr, key) => {
	let resArr = []
	if (Array.isArray(arr)) {
		resArr = arr?.reduce((acc, current) => {
			const x = acc.find(item => item[key] === current[key]);
			if (!x) {
				acc.push(current)
			}
			return acc;
		}, []);
	}
	return resArr
}

// 处理错误返回上一页
export const errGoBack = () => {
	setTimeout(() => {
		uni.navigateBack(-1)
	}, 300)
}

// cloud:// 转 url
export const cloudToUrl = (e) => {
	// console.log(e)
	return new Promise((resolve, reject) => {
		uniCloud.getTempFileURL({
			fileList: [e]
		}).then(res => {
			resolve(res.fileList[0].tempFileURL)
		}).catch(err => {
			reject(err)
		})
	})
}
// cloud:// 转 url 数组类型
export const cloudToUrlArr = (e) => {
	if(e.length == 0){
		return Promise.reject('数组为空');
	}
	return new Promise((resolve, reject) => {
		uniCloud.getTempFileURL({
			fileList: e
		}).then(res => {
			resolve(res.fileList)
		}).catch(err => {
			reject(err)
		})
	})
}

/**
 * 公共的cloud:// 转 url 同步无需异步请求直接拼接字符串
 * url cloudID		例如 cloud://env-00jxhapj7v5l/avatar/673566cefae0dc2ed5b605061731633272475.jpg
 * baseUrl 云存储基本路径		例如 https://env-00jxhapj7v5l.normal.cloudstatic.cn
 * 返回	https://env-00jxhapj7v5l.normal.cloudstatic.cn/avatar/673566cefae0dc2ed5b605061731633272475.jpg
 */
export const publicCloudUrlToHttpUrl = (url, baseUrl = "https://env-00jxhapj7v5l.normal.cloudstatic.cn") => {
	const parts = url.split('/');
	const extractedContent = parts.slice(3).join('/'); // 获取前三个部分并重新拼接
	return baseUrl + '/' + extractedContent;
}

// 传入userInfo对象，返回头像url，无头像返回默认头像
export const avatarHandler = (userInfo) =>{
	if (userInfo.avatar_file && userInfo.avatar_file.url != '') {
		const {name, url} = userInfo.avatar_file
		if (url.substring(0, 8) == "cloud://") {
			return "https://env-00jxhapj7v5l.normal.cloudstatic.cn/" + name
		}else{
			return url
		}
	}else{
		// console.log('false');
		return defaultAvatar
	}
}
export const imageHandler = (durl) =>{
	if (durl.substring(0, 8) == "cloud://") {
		const parts = durl.split('/');
		const result = parts[3] + '/' + parts.slice(4).join('/');  // 这里确保能够获取到后面的部分
		return "https://env-00jxhapj7v5l.normal.cloudstatic.cn/" + result
	}else{
		return defaultAvatar
	}
		
}

// rpx转px
export function rpxToPx(rpx) {
  // 假设设计稿的宽度是 750rpx
  const designWidth = 750; 
  const screenWidth = wx.getSystemInfoSync().screenWidth; // 获取屏幕宽度
  return (rpx / designWidth) * screenWidth; 
}


// 格式化时间戳成 YYYY/MM/DD HH:mm:ss
export function formatTimestamp(timestamp) {
  const date = new Date(timestamp); // 创建 Date 对象
  const year = date.getFullYear(); // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补充 0
  const day = String(date.getDate()).padStart(2, '0'); // 获取日期并补充 0
  const hours = String(date.getHours()).padStart(2, '0'); // 获取小时并补充 0
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补充 0
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒数并补充 0

  // 按照 "YYYY/MM/DD HH:mm:ss" 格式拼接
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}


export function uniqueHistory(){
	// 浏览历史 去重
	// console.log(historyImageArr)
	const historyImageArr = unique(uni.getStorageSync('historyInfo_img'), '_id')
	// const historyVideoArr = unique(uni.getStorageSync('historyInfo_video'), 'video_url')
	// 保存
	uni.setStorageSync('historyInfo_img', historyImageArr)
	// uni.setStorageSync('historyInfo_video', historyVideoArr)
	// 下载历史 去重
	const downloadImageArr = unique(uni.getStorageSync('downloadInfo_img'), '_id')
	// const downloadVideoArr = unique(uni.getStorageSync('downloadInfo_video'), 'video_url')
	// 保存
	uni.setStorageSync('downloadInfo_img', downloadImageArr)
	// uni.setStorageSync('downloadInfo_video', downloadVideoArr)
}

